<?php

namespace App\Controllers\Diary;

use App\Models\Diary\Topic;

class GetNewlestActivity extends \App\Libs\Base\BaseAction
{

    protected function beforeRun()
    {
        parent::beforeRun();
        //$this->needLogin = TRUE;
    }

    /**
     * @return array 返回开启显示的最新一期的5条日记
     */
    public function execute()
    {

        //获取展示的，推荐的，最新的

        $recTopic = Topic::findAll([
            'conditions' => 'is_rec=1 and isshow=1',
            'order' => 'utime desc',
            'limit' => 2
        ]);

        //如果有，。。。如果没有。。。
        if ($recTopic->valid()) {
            if(count($recTopic) ==2){
                $topicModel = new Topic();
                $period = $topicModel->getNewlestPeriodNum();
                $nowTopic = $topicModel->getTopicDetail($period);
                $finalData = [];
                $finalData['mid'] = $nowTopic;
                $finalData['left'] = $recTopic->getFirst();
                $finalData['right'] = $recTopic->GetLast();
		foreach($finalData as $k=>$v){
			$finalData[$k]->id = $v->period;
		}
                return \App\Libs\Views\Json::view(0, '成功', $finalData);

            }else{
                //只有一个推荐的时候，
                $topicModel = new Topic();
                $period = $topicModel->getNewlestPeriodNum();
                $nowTopic = $topicModel->getTopicDetail($period);
                //处理右边的推荐;
                $rightTopic = Topic::find([
                    'conditions' =>'isshow=1 and is_rec=0 and period<>?1',
                    'order'=> 'period desc',
                    'bind'=>[1=>$period]
                ]);
                $finalData['mid'] = $nowTopic;
                $finalData['left'] = $recTopic->getFirst();
                $finalData['right'] =$rightTopic;
		foreach($finalData as $k=>$v){
			$finalData[$k]->id = $v->period;
		}
                return \App\Libs\Views\Json::view(0, '成功', $finalData);

            }

        } else {
            $finalTopic = Topic::findAll([
                'conditions' => 'isshow=1',
                'order' => 'period desc',
                'limit' => 3
            ])->toArray();
            $finalData = [];
            $finalData['mid'] = current($finalTopic);
            $finalData['left'] = next($finalTopic);
            $finalData['right'] = next($finalTopic);
            foreach($finalData as $key =>  $val){
                if(empty($finalData[$key])){
                    $finalData[$key] = $finalData['mid'];
                }
            }
            return \App\Libs\Views\Json::view(0, '成功', $finalData);
        }

    }
}
